package serverController;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.passClass.PassData;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerThread implements Runnable {
    private static ServerSocket server;

    static {
        try {
            server = new ServerSocket(10086);
            System.out.println("Server host:"+ InetAddress.getLocalHost());
            System.out.println("Server port:"+ server.getLocalPort());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        receive();
    }

    public static void receive(){
        try{
            Socket accept = server.accept();
            System.out.println("\n"+Thread.currentThread().getName()+":Client accepted");
            Runnable r = new ServerThread();
            Thread t1 = new Thread(r);
            t1.setDaemon(true);
            t1.start();

            InputStream in = accept.getInputStream();
            OutputStream out = accept.getOutputStream();

            byte[] bytes = new byte[4096];
            int len = in.read(bytes);                       //接收路径
            String path = new String(bytes,0,len);
            String[] paths = path.substring(1).split("/");

            out.write("received".getBytes());               //响应客户端
            out.flush();


            len = in.read(bytes);                           //接收参数
            String args = new String(bytes,0,len);

            PassData send = MainNavigator.fromPath(paths,args);     //计算响应数据
            System.out.println(send.getMessage());
            out.write(send.getClass().getName().getBytes());        //向客户端输出响应数据
            out.flush();

            ObjectMapper om = new ObjectMapper();
            om.writeValue(out,send);

            in.close();
            out.close();
            accept.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Runnable r = new ServerThread();
        Thread t0 = new Thread(r);
        t0.setDaemon(true);
        t0.start();
        Scanner scanner = new Scanner(System.in);
        while(!scanner.next().equals("server_shutdown"));
    }
}
